#include "PCH.h"
#include "Window.h"

const LPSTR const Window::CLASS_NAME = "EngineClass";
const LPSTR const Window::TITLE = "Direct Engine";

Window::Window(void) throw(EngineException*) : m_graphic(new Engine)
{
	this->RegistClass();
	this->CreateWindow();
	this->m_graphic->Init();
}


Window::~Window(void)
{
}

void Window::RegistClass( void ) throw(EngineException*)
{
	WNDCLASSEX wc;
	wc.cbSize = sizeof( WNDCLASSEX );
	wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;;
	wc.lpfnWndProc = WndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = GetModuleHandle(NULL);
	wc.hIcon = LoadIcon( NULL, IDI_APPLICATION );
	wc.hCursor = LoadCursor( NULL, IDC_ARROW );
	wc.hbrBackground =( HBRUSH )( COLOR_WINDOW + 1 );
	wc.lpszMenuName = NULL;
	wc.lpszClassName = Window::CLASS_NAME;
	wc.hIconSm = LoadIcon( NULL, IDI_APPLICATION );

	if(!RegisterClassEx(&wc))
		throw new EngineException("Register Class Error");
}

void Window::CreateWindow( void ) throw(EngineException*)
{
	this->m_hWnd = CreateWindowEx( WS_EX_CLIENTEDGE, CLASS_NAME, TITLE, WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, CW_USEDEFAULT, 240, 120, NULL, NULL, GetModuleHandle(NULL), NULL );

	if(!this->m_hWnd)
		throw new EngineException("Create Window Error");

	ShowWindow(this->m_hWnd, SW_NORMAL);
	UpdateWindow(this->m_hWnd);
}

void Window::Loop( void )
{
	MSG msg;
	ZeroMemory(&msg, sizeof(MSG));

	while(msg.message != WM_QUIT)
	{
		if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else
		{
				
		}

	}
}

LRESULT Window::MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
	return DefWindowProc(hWnd, msg, wParam, lParam);
}



LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
	switch(msg) {
	case WM_DESTROY:
			PostQuitMessage(0);
			return 0;

	case WM_CLOSE:
			PostQuitMessage(0);		
			return 0;

	default:
			return wnd->MsgProc(hWnd, msg, wParam, lParam);	
	}
}
